<template>
	<div id="wx_qrcode"></div>
</template>
<script>
import { login } from "@/api/request"
import {mapActions} from "vuex"
export default {
  watch:{
      $route(to, from) {
          // 对路由变化作出响应...
          // console.log('loginto',to)
          console.log('loginfrom',from)
      }
  },
	mounted() {
    let host = window.location.host
    console.log("host",host)
    console.log("glroute",this.$store.state.routes.originRouteFrom)
    let url = window.location.href
    var name ="code";
    var code = this.getParam(url,name);
    if(host.includes('8047')){
      this.mockLogin()
    }else{
      if(this.$store.state.user.userInfo.token){
        let route = ''
        if(this.$store.state.routes.originRouteFrom.path){
          this.$router.push({
            path:this.$store.state.routes.originRouteFrom.path,
            query:this.$store.state.routes.originRouteFrom.query
          })
        }else{
          route = this.$store.state.routes.routeList[0].items[0].route || '/asset/assetHome'
          this.$router.push(route)
        }
      }else if(code){
        this.login(code)
      }else{
        this.jugeEnv()
      }
    }
	},
  methods:{
    ...mapActions('user', ["setUserInfo","setSignInfo"]),
    mockLogin(){
      let userInfo =  {
			"usertype": null,
			"wxUserId": "DaFei",
			"token": "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX3V1aWQiOiIzMTBkOWU1N2EzYTE5NWQyN2YxN2MwZmMwZDhiOTQ4OSIsImV4cCI6MTY5OTAyMDM3Mn0.B4QGVtH90ITD4wb_YbRtITZVrDu6Mg1X48uiD5NTZcHxbYhwdsQYmU6tqoDVDc2k3KeGZivkLJ9cQAaQmvurzg",
			"name": "大飞",
			"uuid": null,
			"expireTime": 1646104892277,
			"loginTime": 1645932092277,
			"moduleId": null,
			"avatar": "https://wework.qpic.cn/bizmail/1GPMXZvy72fcTLXW3z6n1A8eu7cJtOuzYG6iaerOliaaicnib2L2kwbtUg/0",
			"groupId": "7f477cb088fead381362d6314994bd45",
			"groupName": "测试审批人组",
			"depName": "项目研发组",
			"errcode": 0,
			"depId": "33",
			"userId": "6edf9e3e416e422badafe4f13c891191"
		}
      this.setUserInfo(userInfo)
      let route = ''
      if(this.$store.state.routes.originRouteFrom.path){
        this.$router.push({
          path:this.$store.state.routes.originRouteFrom.path,
          query:this.$store.state.routes.originRouteFrom.query
        })
      }else{
        route =  this.$store.state.routes.routeList.length>0 ? this.$store.state.routes.routeList[0].items[0].route : '/asset/assetHome'
        this.$router.push(route)
      }
    },
    getParam(url, name) {
      try {
          var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
          var r = url.split('?')[1].match(reg);
          if(r != null) {
            return r[2];
          }
          return "";//如果此处只写return;则返回的是undefined
      } catch(e) {
          return "";//如果此处只写return;则返回的是undefined
      }
    },

    // 判断是否是微信环境，不是的话用扫码登录的方式
    jugeEnv(){
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            this.doLogin()
        }else{
          this.scanLogin()
        }
    },
    doLogin() {
				let _this = this
				localStorage.setItem("hasLogin",true)
				// 这里放自己的域名
				let redirect_uri = encodeURIComponent(this.glConfig.redirect_uri)
				let authorUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+this.glConfig.APPID+'&redirect_uri='+redirect_uri+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
				window.location.href = authorUrl
			},
    scanLogin(){
      window.WwLogin({
        id: 'wx_qrcode', // 登录页面显示二维码的容器id
        appid: this.glConfig.APPID, // 企业微信的CorpID，在企业微信管理端查看
        agentid: this.glConfig.agentid, // 授权方的网页应用id，在具体的网页应用中查看
        redirect_uri: encodeURIComponent(this.glConfig.redirect_uri), // 重定向的地址，需要进行encode
        // redirect_uri: encodeURIComponent("http://localhost:8047/login"), // 重定向的地址，需要进行encode
        scope:"snsapi_userinfo"
      })
    },
    login(code){
      let _data = {
        code: code
      }
      this.glRequest.login(_data).then(res => {
        if(res.code == "0000"){
          this.setUserInfo(res.data)
          if(this.$store.state.routes.originRouteFrom.path){
            this.$router.push({
              path:this.$store.state.routes.originRouteFrom.path,
              query:this.$store.state.routes.originRouteFrom.query
            })
          }else{
            let route = this.$store.state.routes.routeList.length>0? this.$store.state.routes.routeList[0].items[0].route : '/asset/assetHome'
            this.$router.push(route)
          }
        }else{
          this.jugeEnv()
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
#wx_qrcode{
  width:100%;
  height:auto;

  /deep/iframe{
    width:100%;
    margin-top:30px;
  }
}
</style>